package com.baidu.navi.sdkdemo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import net.lbh.baidumap.BaiduMapAgent;
import net.lbh.baidumap.BaiduMapAgent.CoordType;
import net.lbh.baidumapdemo.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.OnHierarchyChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNRoutePlanNode.CoordinateType;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.baidu.navisdk.adapter.BaiduNaviManager.NaviInitListener;
import com.baidu.navisdk.adapter.BaiduNaviManager.RoutePlanListener;
import com.baidu.navisdk.comapi.base.BNObserver;
import com.baidu.navisdk.comapi.base.BNSubject;
import com.baidu.navisdk.comapi.routeplan.BNRoutePlaner;
import com.baidu.navisdk.ui.widget.RoutePlanObserver;

public class BNDemoMainActivity extends Activity {

	public static final String TAG = "NaviSDkDemo";
	private static final String APP_FOLDER_NAME = "BNSDKDemo";
	private Button mWgsNaviBtn = null;
	private Button mGcjNaviBtn = null, testBtn;
	private Button mBdmcNaviBtn = null;
	private static String mSDCardPath = null;

	private EditText fromLatitudeEdt, fromLongitudeEdt, toLatitudeEdt,
			toLongitudeEdt, fromAddressEdt, toAddressEdt;

	private double fromLatitude;
	private double fromLongitude;
	private double toLatitude;
	private double toLongitude;

	private String fromAddress, toAddress, curCity;

	private int mClickMapCount;
	public static final String ROUTE_PLAN_NODE = "routePlanNode";

	private MapView mMapView;

	private BaiduMapAgent mMapAgent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_bn_main);
		mMapView = (MapView) findViewById(R.id.bn_mapView);
		// mMapAgent = BaiduMapAgent.newInstance(mMapView);
		mMapAgent = new BaiduMapAgent(mMapView);
		mWgsNaviBtn = (Button) findViewById(R.id.wgsNaviBtn);
		mGcjNaviBtn = (Button) findViewById(R.id.gcjNaviBtn);
		mBdmcNaviBtn = (Button) findViewById(R.id.bdmcNaviBtn);
		fromLatitudeEdt = (EditText) findViewById(R.id.s_paln_la);
		fromLongitudeEdt = (EditText) findViewById(R.id.s_paln_lo);
		toLatitudeEdt = (EditText) findViewById(R.id.e_paln_la);
		toLongitudeEdt = (EditText) findViewById(R.id.e_paln_lo);
		fromAddressEdt = (EditText) findViewById(R.id.s_paln_ad);
		toAddressEdt = (EditText) findViewById(R.id.e_paln_ad);

		initListener();
		if (initDirs()) {
			initNavi(this);
		}

		initLocation();
	}

	boolean isFirLoc = true;

	void initLocation() {

		mMapAgent.startLocation( new BDLocationListener() {

			@Override
			public void onReceiveLocation(BDLocation location) {

				if (location == null || mMapView == null)
					return;
				BDLocation gcj02Pos = BaiduMapAgent.convertBd09llToGcj02(location);

				curCity = location.getCity();
				mMapAgent.setMyLocationData(location);

				if (isFirLoc) {
					Toast.makeText(BNDemoMainActivity.this,
							"coorType :" + location.getCoorType(), 0).show();
					isFirLoc = false;
					mMapAgent.movePositionToCenter(location);
					mMapAgent.setMapViewZoomTo(0);

					fromLatitude = gcj02Pos.getLatitude();
					fromLongitude = gcj02Pos.getLongitude();
					fromLatitudeEdt.setText(String.valueOf(fromLatitude));
					fromLongitudeEdt.setText(String.valueOf(fromLongitude));
					fromAddress = gcj02Pos.getAddrStr();
					fromAddressEdt.setText(fromAddress);
				}
			}
		});

		mMapAgent.setOnMapViewClick(new OnMapClickListener() {

			@Override
			public boolean onMapPoiClick(MapPoi arg0) {

				BDLocation gcj02Pos = BaiduMapAgent.convertBd09llToGcj02(arg0.getPosition());

				Toast.makeText(
						BNDemoMainActivity.this,
						"国测局  经度：" + gcj02Pos.getLatitude() + "维度："
								+ gcj02Pos.getLongitude(), 0).show();

				mClickMapCount++;
				if (mClickMapCount % 2 != 0) {
					mMapAgent.clearAllMarkers();

					fromLatitude = gcj02Pos.getLatitude();
					fromLongitude = gcj02Pos.getLongitude();
					fromLatitudeEdt.setText(String.valueOf(fromLatitude));
					fromLongitudeEdt.setText(String.valueOf(fromLongitude));
					fromAddress = arg0.getName();
					fromAddressEdt.setText(fromAddress);
					mMapAgent.addMarker(arg0.getPosition(), R.drawable.icon_st);
					mMapAgent.movePositionToCenter(arg0.getPosition());

				} else {

					toLatitude = gcj02Pos.getLatitude();
					toLongitude = gcj02Pos.getLongitude();
					toLatitudeEdt.setText(String.valueOf(toLatitude));
					toLongitudeEdt.setText(String.valueOf(toLongitude));
					toAddress = arg0.getName();
					toAddressEdt.setText(toAddress);
					mMapAgent.addMarker(arg0.getPosition(), R.drawable.icon_en);
					mMapAgent.movePositionToCenter(arg0.getPosition());
					mClickMapCount = 0;

				}

				return false;
			}

			@Override
			public void onMapClick(LatLng arg0) {

				BDLocation gcj02Pos = BaiduMapAgent.convertBd09llToGcj02(arg0);
				
				Toast.makeText(BNDemoMainActivity.this,
						"国测局 经度：" + gcj02Pos.getLatitude() + "维度：" + gcj02Pos.getLongitude(), 0)
						.show();

				mClickMapCount++;

				if (mClickMapCount % 2 != 0) {

					mMapAgent.clearAllMarkers();
					fromLatitude = gcj02Pos.getLatitude();
					fromLongitude = gcj02Pos.getLongitude();
					fromLatitudeEdt.setText(String.valueOf(fromLatitude));
					fromLongitudeEdt.setText(String.valueOf(fromLongitude));
					fromAddress = "";
					fromAddressEdt.setText(fromAddress);
					mMapAgent.addMarker(arg0, R.drawable.icon_st);
					mMapAgent.movePositionToCenter(arg0);

				} else {

					toLatitude =gcj02Pos.getLatitude();
					toLongitude = gcj02Pos.getLongitude();
					toLatitudeEdt.setText(String.valueOf(toLatitude));
					toLongitudeEdt.setText(String.valueOf(toLongitude));
					toAddress = "";
					toAddressEdt.setText(toAddress);
					mMapAgent.addMarker(arg0, R.drawable.icon_en);
					mMapAgent.movePositionToCenter(arg0);
					mClickMapCount = 0;

				}
			}
		});
	}

	@Override
	protected void onResume() {

		super.onResume();
	}

	private void initListener() {
		if (mWgsNaviBtn != null) {
			mWgsNaviBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					if (BaiduNaviManager.isNaviInited()) {
						routeplanToNavi(CoordinateType.WGS84);

					}
				}
			});
		}
		if (mGcjNaviBtn != null) {
			mGcjNaviBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					if (BaiduNaviManager.isNaviInited()) {

						routeplanToNavi(CoordinateType.GCJ02);
					}
				}
			});
		}
		if (mBdmcNaviBtn != null) {
			mBdmcNaviBtn.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					if (BaiduNaviManager.isNaviInited()) {
						test = false;
						routeplanToNavi(CoordinateType.BD09_MC);
					}
				}
			});
		}
	}

	public static boolean initDirs() {
		mSDCardPath = getSdcardDir();
		if (mSDCardPath == null) {
			return false;
		}
		File f = new File(mSDCardPath, APP_FOLDER_NAME);
		if (!f.exists()) {
			try {
				f.mkdir();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	boolean test;
	static String authinfo = null;

	public void initNavi(final Context context) {
		BaiduNaviManager.getInstance().setNativeLibraryPath(
				mSDCardPath + "/BaiduNaviSDK_SO");
		BaiduNaviManager.getInstance().init((Activity) context, mSDCardPath,
				APP_FOLDER_NAME, new NaviInitListener() {
					@Override
					public void onAuthResult(int status, String msg) {
						if (0 == status) {
							authinfo = "key校验成功!";
						} else {
							authinfo = "key校验失败, " + msg;
						}
						((Activity) context).runOnUiThread(new Runnable() {

							@Override
							public void run() {
								Log.d("", authinfo);
								Toast.makeText(context, authinfo,
										Toast.LENGTH_LONG).show();
							}
						});

					}

					public void initSuccess() {
						Toast.makeText(context, "百度导航引擎初始化成功",
								Toast.LENGTH_SHORT).show();
					}

					public void initStart() {
						Toast.makeText(context, "百度导航引擎初始化开始",
								Toast.LENGTH_SHORT).show();
					}

					public void initFailed() {
						Toast.makeText(context, "百度导航引擎初始化失败",
								Toast.LENGTH_SHORT).show();
					}
				}, null /* mTTSCallback */);
	}

	private static String getSdcardDir() {
		if (Environment.getExternalStorageState().equalsIgnoreCase(
				Environment.MEDIA_MOUNTED)) {
			return Environment.getExternalStorageDirectory().toString();
		}
		return null;
	}

	private void routeplanToNavi(CoordinateType coType) {
		BNRoutePlanNode sNode = null;
		BNRoutePlanNode eNode = null;
		if (TextUtils.isEmpty(String.valueOf(fromLatitude))
				|| TextUtils.isEmpty(String.valueOf(fromLongitude))
				|| TextUtils.isEmpty(String.valueOf(toLatitude))
				|| TextUtils.isEmpty(String.valueOf(toLongitude))) {
			Toast.makeText(this, "请输入 或 选择 起始地址！", 0).show();
			return;
		}

		switch (coType) {
		case GCJ02: {
			sNode = new BNRoutePlanNode(fromLongitude, fromLatitude,
					fromAddress, null, coType);
			eNode = new BNRoutePlanNode(toLongitude, toLatitude, toAddress,
					null, coType);

			// sNode = new BNRoutePlanNode(116.30142, 40.05087, "百度大厦", null,
			// coType);
			// eNode = new BNRoutePlanNode(116.39750, 39.90882, "北京天安门", null,
			// coType);

			break;
		}
		case WGS84: {
			sNode = new BNRoutePlanNode(fromLongitude, fromLatitude,
					fromAddress, null, coType);
			eNode = new BNRoutePlanNode(toLongitude, toLatitude, toAddress,
					null, coType);

//			sNode = new BNRoutePlanNode(116.300821, 40.050969, "百度大厦", null,
//					coType);
//			eNode = new BNRoutePlanNode(116.397491, 39.908749, "北京天安门", null,
//					coType);

			break;
		}
		case BD09_MC: {
			// sNode = new BNRoutePlanNode(12947471, 4846474, "百度大厦", null,
			// coType);
			// eNode = new BNRoutePlanNode(12958160, 4825947, "北京天安门", null,
			// coType);

			sNode = new BNRoutePlanNode(fromLongitude, fromLatitude,
					fromAddress, null, coType);
			eNode = new BNRoutePlanNode(toLongitude, toLatitude, toAddress,
					null, coType);

			if (test) {
				sNode = new BNRoutePlanNode(12947471, 4846474, "百度大厦", null,
						coType);
				eNode = new BNRoutePlanNode(12958160, 4825947, "北京天安门", null,
						coType);

			}
			break;
		}
		default:
			;
		}
		if (sNode != null && eNode != null) {
			List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
			list.add(sNode);
			list.add(eNode);
			BaiduNaviManager.getInstance().launchNavigator(this, list, 1, true,
					new DemoRoutePlanListener(sNode));

		}
	}

	public class DemoRoutePlanListener implements RoutePlanListener {

		private BNRoutePlanNode mBNRoutePlanNode = null;

		public DemoRoutePlanListener(BNRoutePlanNode node) {
			mBNRoutePlanNode = node;
		}

		@Override
		public void onJumpToNavigator() {
			Intent intent = new Intent(BNDemoMainActivity.this,
					BNDemoGuideActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable(ROUTE_PLAN_NODE,
					(BNRoutePlanNode) mBNRoutePlanNode);
			intent.putExtras(bundle);
			startActivity(intent);
		}

		@Override
		public void onRoutePlanFailed() {
			// TODO Auto-generated method stub
			Log.e("", " --onRoutePlanFailed --");
			Toast.makeText(BNDemoMainActivity.this, "路线规划失败！", 0).show();
		}
	}

	private BNOuterTTSPlayerCallback mTTSCallback = new BNOuterTTSPlayerCallback() {

		@Override
		public void stopTTS() {
			// TODO Auto-generated method stub

		}

		@Override
		public void resumeTTS() {
			// TODO Auto-generated method stub

		}

		@Override
		public void releaseTTSPlayer() {
			// TODO Auto-generated method stub

		}

		@Override
		public int playTTSText(String speech, int bPreempt) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public void phoneHangUp() {
			// TODO Auto-generated method stub

		}

		@Override
		public void phoneCalling() {
			// TODO Auto-generated method stub

		}

		@Override
		public void pauseTTS() {
			// TODO Auto-generated method stub

		}

		@Override
		public void initTTSPlayer() {
			// TODO Auto-generated method stub

		}

		@Override
		public int getTTSState() {
			// TODO Auto-generated method stub
			return 0;
		}
	};
}
